<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>马赛克</title>
		<style type="text/css">
			*{margin: 0;padding: 0;background: gray;}
			#text{position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;}
		</style>
		<script type="text/javascript">
			window.onload=function(){
				var canvas=document.querySelector("#text");
				if(canvas.getContext){
					var ctx=canvas.getContext("2d");
					var img=new Image();
					img.src="img/马赛克.png";
					img.onload=function(){
						canvas.width=img.width*2;
						canvas.height=img.height;
						draw();
					}
					function draw(){
						ctx.drawImage(img,0,0);
						var oldImgdata=ctx.getImageData(0,0,img.width,img.height);
						var newImgdata=ctx.createImageData(img.width,img.height);

						var size=7;
						for (var i=0;i<oldImgdata.width/size;i++) {
							for (var j=0;j<oldImgdata.height/size;j++) {
								var color=getPxinfo(oldImgdata,i*size+(Math.floor(Math.random()*size)),j*size+(Math.floor(Math.random()*size)));
								for (var a=0;a<size;a++) {
									for(var b=0;b<size;b++){
										setPxinfo(newImgdata,i*size+a,j*size+b,color);
									}
								}
							}
						}
						ctx.putImageData(newImgdata,img.width,0);
					}

					function getPxinfo(imgdata,x,y){
						var color=[];
						var data =imgdata.data;
						var w=imgdata.width;
						var h=imgdata.height;
						color[0]=data[(y*w+x)*4];
						color[1]=data[(y*w+x)*4+1];
						color[2]=data[(y*w+x)*4+2];
						color[3]=data[(y*w+x)*4+3];
						return color;
					}

					function setPxinfo(imgdata,x,y,color){
						var data=imgdata.data;
						var w=imgdata.width;
						var h=imgdata.height;
						data[(y*w+x)*4]=color[0];
						data[(y*w+x)*4+1]=color[1];
						data[(y*w+x)*4+2]=color[2];
						data[(y*w+x)*4+3]=color[3];
					}
				}

			}
		</script>
	</head>
	<body>
		<canvas id="text" width="200" height="200"></canvas>
	</body>
</html>
